package com.yihu.cms.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yihu.beans.Artwork;
import com.yihu.beans.dic.DatadicQuery;
import com.yihu.beans.dic.Resource;
import com.yihu.cms.bean.comment.Comment;
import com.yihu.cms.service.ArtworkQueryService;
import com.yihu.cms.service.ArtworkService;
import com.yihu.cms.service.DataDictionaryService;
import com.yihu.cms.service.UserService;
import com.yihu.cms.util.HttpUtils;
import com.yihu.cms.util.Osslog;
import com.yihu.web.bean.Attention;
import com.yihu.web.bean.Channel;
import com.yihu.web.bean.ChannelGoods;
import com.yihu.web.bean.ChannelGoodsList;
import com.yihu.web.bean.user.User;
import com.yihu.web.bean.vo.ArtworkQuery;
import com.yihu.web.bean.vo.AttentionParam;
import com.yihu.web.bean.vo.ChannelGoodsQuery;
import com.yihu.web.bean.vo.ChannelQuery;
import com.yihu.web.bean.vo.StockVO;
import com.yihu.web.constats.DSConstants;
import com.yihu.web.utils.FormatDateTime;
import com.yihu.web.utils.InfoHelp;
import com.yihu.web.utils.PropertiesUtil;

@Controller
public class ArtworkController extends BaseController {

	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private HttpServletRequest request;

	private ArtworkService as = new ArtworkService();
	ArtworkQueryService service = new ArtworkQueryService();

	@RequestMapping(value = "/artwork", method = RequestMethod.POST)
	public @ResponseBody Object create(@Valid @RequestBody Artwork artwork, BindingResult vResult) {
		log.info("create artwork .");
		if (vResult.hasErrors()) {
			List<ObjectError> errorList = vResult.getAllErrors();
			for (ObjectError error : errorList) {
				log.error("validate data error . error message = " + error.getDefaultMessage());
			}
			return getResult(1);
		}
		int result = as.add(artwork);
		log.info("result=" + result);
		service.setTeaTotal(new ArtworkQuery());
		return getResult(result, null);
	}

	@RequestMapping(value = "/artwork", method = RequestMethod.PUT)
	public @ResponseBody Object updateArtwork(@RequestBody Artwork artwork, BindingResult vResult) {
		log.info("update artwork name = " + artwork.getName());
		int result = as.update(artwork);
		log.info("result=" + result);
		service.setTeaTotal(new ArtworkQuery());
		return getResult(result, null);
	}

	@RequestMapping(value = "/artwork/{id}", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteArtwork(@PathVariable("id") String id) {
		// @PathVariable 当使用@RequestMapping URI template 样式映射时， 即
		// someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
		log.info("del artwork id=" + id);
		int result = as.del(id);
		log.info("result=" + result);
		service.setTeaTotal(new ArtworkQuery());
		return getResult(result, null);
	}

	@RequestMapping(value = "/artwork/{id}", method = RequestMethod.GET)
	public @ResponseBody Artwork getArtwork(@PathVariable("id") String id) {
		log.info("get artwork id=" + id);
		// String artworkJson = as.getById(id);
		Artwork a = as.getById(id);
		
		return a;
	}

	/***
	 * 更改库存
	 * 
	 * @param stock
	 * @return
	 */
	@RequestMapping(value = "/artwork/stock", method = RequestMethod.PUT)
	public @ResponseBody Object updateStock(@RequestBody StockVO stock) {
		Osslog.info("updateStock = " + stock);
		return service.updateStock(stock);
	}

	/***
	 * 无货的情况下，用户设置补货提醒
	 * 
	 * @param id:artworkid，
	 *        openid: 微信用户Id
	 *            
	 * @return
	 */
	@RequestMapping(value = "/artwork/book", method = RequestMethod.POST)
	public @ResponseBody Object bookArtwork(@RequestBody StockVO stock) {
		Osslog.debug("into bookArtwork: " + stock);
		stock.setType(1);
		Cookie[] cookies = request.getCookies();
		if (StringUtils.isBlank(stock.getOpenid())) {
			for (Cookie c : cookies) {
				String name = c.getName();
				if ("wxuser".equals(name)) {
					// logger.debug("cookie.userId: "+c.getValue());
					String userJson = InfoHelp.unescape(c.getValue());
					User user = JSON.parseObject(userJson, User.class);
					String openid = String.valueOf(user.getOpenid());
					stock.setOpenid(openid);
					break;
				}
			}
		}
		return service.updateStock(stock);
	}

	// yihuds
	@RequestMapping(value = "/artwork/list", method = RequestMethod.GET)
	public @ResponseBody Object getArtWorks(ArtworkQuery query) {
		// yihuds
		Osslog.debug("getArtWorks: " + query);
		long userId = getUserIdFromCookie();
		query.setUserId(userId);
		Osslog.debug("getArtWorks.cookie.userId: " + userId);
		// encodeStr(query);
		return service.getArtworkByCategory(query);
	}
	
	/***
	 * 获取主页数据
	 * @param query yihuds
	 * @return
	 */
	@RequestMapping(value = "/artwork/home", method = RequestMethod.GET)
	public @ResponseBody Object getHomeData(ArtworkQuery query) {
		// yihuds
		Osslog.debug("getHomeData: " + query);
		long userId = getUserIdFromCookie();
		query.setUserId(userId);
		Osslog.debug("getHomeData.cookie.userId: " + userId);	
		return service.getHomeData(query);
	}
	
	/***
	 * 获取主页数据
	 * @param query yihuds
	 * @return
	 */
	@RequestMapping(value = "/artwork/home/v2", method = RequestMethod.GET)
	public @ResponseBody Object getHomeDataV2(ArtworkQuery query) {
		// yihuds
		Osslog.debug("getHomeData: " + query);
		long userId = getUserIdFromCookie();
		query.setUserId(userId);
		query.setV2(true);
		Osslog.debug("getHomeData.cookie.userId: " + userId);	
		return service.getHomeData(query);
	}
	
	// yihuds
	@RequestMapping(value = "/artwork/list/related", method = RequestMethod.GET)
	public @ResponseBody Object getArtWorksByRelated(ArtworkQuery query) {
		// yihuds
		Osslog.debug("getArtWorksByRelated: " + query);
		String relatedid = query.getRelatedid();
		String rid[] = relatedid.split(",");
		long userId = getUserIdFromCookie();
		query.setUserId(userId);
		query.setRelatedids(rid);
		return service.getArtWorksByRelated(query);
	}

	private long getUserIdFromCookie() {
		long userId = 0;
		Cookie[] cookies = request.getCookies();	
		if(cookies==null)
			return userId;
		try{
			for (Cookie c : cookies) {
				String name = c.getName();
				if ("wxuser".equals(name)) {
					// logger.debug("cookie.userId: "+c.getValue());
					String userJson = InfoHelp.unescape(c.getValue());
					User user = JSON.parseObject(userJson, User.class);
					userId = user.getUserId();				
					break;
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}	
		return userId;
	}

	@RequestMapping(value = "/service/tea/total", method = RequestMethod.GET)
	public @ResponseBody Object getTeaTotal(ArtworkQuery aQuery) {
		// yihuds
		ArtworkQueryService service = new ArtworkQueryService();
		return service.getTeaTotal(aQuery);
	}
	
	@RequestMapping(value = "/service/tea/setTotal", method = RequestMethod.GET)
	public @ResponseBody Object setTeaTotal(ArtworkQuery aQuery) {
		// yihuds
		ArtworkQueryService service = new ArtworkQueryService();
		return service.setTeaTotal(aQuery);
	}

	public static void main(String args[]) {
		
		// ArtworkController ac = new ArtworkController();
		// Map<String, Object> result = ac.getResult(1, null);
		// System.out.println("result = " + JSON.toJSONString(result));
		ArtworkController ac = new ArtworkController();
		Comment c = new Comment();

		/*
		 * c.setContent("aaaa"); User from = new User(); from.setUserId(1);
		 * from.setUserName("a1"); c.setFrom(from); Product p = new Product();
		 * p.setId("3432dsfsdf"); p.setName("p1"); c.setProduct(p);
		 */

		/*
		 * Attachment a = new Attachment(); a.setParentFolder("555");
		 * a.setFileid("AAADDFDFDF"); a.setFilename("a1"); a.setFiletype("img");
		 * Activity a = new Activity(); a.setPrice(0); a.setSubject("aaa");
		 */
		// a.setTime("2010-10-12 8-10");
		// Artwork a = new Artwork();
		// a.setName("aa");
		// ArtworkAuthor artworkAuthor = new ArtworkAuthor();
		// artworkAuthor.setCid("A");
		// artworkAuthor.setName("qibaishi");
		// ArtworkType type = new ArtworkType();
		// type.setName("chawenhua");
		// ArtworkFont font = new ArtworkFont();
		// font.setCid("c1");
		// font.setName("kaishu");
		// ArtworkParentType parent = new ArtworkParentType();
		// parent.setName("ziti");
		// font.setParent(parent);
		// a.setFont(font);
		// a.setArtworkType(type);
		// a.setArtworkAuthor(artworkAuthor);
		// System.out.println("result = " + JSON.toJSONString(a));
	}

	private void encodeStr(ArtworkQuery query) {
		try {
			if (!StringUtils.isBlank(query.getName())) {
				String name = new String(query.getName().getBytes("ISO-8859-1"), "UTF-8");
				query.setName(name);
			}
			if (!StringUtils.isBlank(query.getKeyword())) {
				String keyword = new String(query.getKeyword().getBytes("ISO-8859-1"), "UTF-8");
				query.setKeyword(keyword);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	/***
	 * 增加提醒
	 * @param a
	 * @return
	 */
	@RequestMapping(value = "/artwork/attention", method = RequestMethod.POST)
	public @ResponseBody Object addAttention(@RequestBody Attention a) {
		log.info("into artwork post.attention: " + a);
		ArtworkQueryService service = new ArtworkQueryService();
		return service.addAttention(a);
	}

	@RequestMapping(value = "/artwork/attention", method = RequestMethod.GET)
	public @ResponseBody Object sendAttention(Attention a) {
		log.info("into artwork.sendAttention: " + a);
		ArtworkQueryService service = new ArtworkQueryService();
		a = (Attention) service.getAttention(a);
		if(a==null){
			return getResult(1, "");
		}
		log.info("getAttention: " + a);
		int type = a.getType();
		List<String> openids = a.getOpenids();
		String attentionurl = PropertiesUtil.getInstance().getProperty("wxserviceurl");
		attentionurl += "/attention";
		AttentionParam param = new AttentionParam();
		String desc = "";
		String url = "";
		if(type==0){
			desc = "秒杀";
			url = "/#/seckill/"+a.getPid()+"/detail";
		}
		else if(type==1){
			desc = "拍卖";
			url = "/#/auction/"+a.getPid()+"/detail";
		}
		else if(type==2){
			desc = "团购";
			url = "/#/groupbuy/"+a.getPid()+"/detail";
		}
		param.setTitle("商品"+desc+"提醒");
		//
		String shangcheng = (char)34 + a.getPname() + (char)34;
		param.setContent("您预约的商品 " + shangcheng +" "+ desc+"5分钟后开始。");
		param.setOpenids(openids);
		param.setDate(a.getStrDate());
		param.setRemark("请提前进入"+desc+"页面...");
		param.setUrl(url);
		// param.setDate("2017-10-12 10:30");
		try {
			String result = HttpUtils.sendPostJson(attentionurl, JSON.toJSONString(param));
			log.info("attention.result: " + result);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getResult(0, "");
	}

	/***
	 * 增加栏目
	 * @param a
	 * @return
	 */
	@RequestMapping(value = "/channel", method = RequestMethod.POST)
	public @ResponseBody Object add(@RequestBody Channel c) {
		log.info("into artwork post.channeladd: " + c);
		return service.addChannel(c);
	}

	@RequestMapping(value = "/channel/{id}", method = RequestMethod.DELETE)
	public @ResponseBody Object delete(@PathVariable("id") String id) {
		log.info("into artwork post.channel.delete: " + id);
		return service.deleteChannelById(id);
	}
	
	@RequestMapping(value = "/channel/update", method = RequestMethod.POST)
	public @ResponseBody Object update(@RequestBody Channel c) {
		log.info("into artwork post.channel.update: " + c);
		return service.updateChannelById(c);
	}
	
	@RequestMapping(value = "/channel/{id}", method = RequestMethod.GET)
	public @ResponseBody Object get(@PathVariable("id") String id) {
		log.info("into artwork post.channel.get: " + id);
		return service.getChannelById(id);
	}
	
	@RequestMapping(value = "/channel/list", method = RequestMethod.GET)
	public @ResponseBody Object list(ChannelQuery query) {
		log.info("into artwork post.channel.list: " + query);
		return service.getChannelsByPage(query);
	}
	
	/***
	 * 增加栏目商品
	 * @param a
	 * @return
	 */
	@RequestMapping(value = "/channelGoods", method = RequestMethod.POST)
	public @ResponseBody Object add(@RequestBody ChannelGoods c) {
		log.info("into artwork post.channelGoods.add: " + c);
		return service.addChannelGoods(c);
	}
	
	/***
	 * post list
	 * @param c
	 * @return
	 */
	@RequestMapping(value = "/channelGoods/list", method = RequestMethod.POST)
	public @ResponseBody Object add(@RequestBody ChannelGoodsList goodsList) {
		log.info("into artwork post.channelGoods.add: " + goodsList);
		return service.addChannelGoodsList(goodsList);
	}

	@RequestMapping(value = "/channelGoods/{id}", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteGoods(@PathVariable("id") String id) {
		log.info("into artwork post.channel.deleteGoods: " + id);
		return service.deleteChannelGoodsById(id);
	}
	
	@RequestMapping(value = "/channelGoods/update", method = RequestMethod.POST)
	public @ResponseBody Object updateGoods(@RequestBody ChannelGoods goods) {
		log.info("into artwork post.ChannelGoods.update: " + goods);
		return service.updateChannelGoodsById(goods);
	}
	
	@RequestMapping(value = "/channelGoods/{id}", method = RequestMethod.GET)
	public @ResponseBody Object getGoods(@PathVariable("id") String id) {
		log.info("into artwork post.channel.getGoods: " + id);
		return service.getChannelGoodsById(id);
	}
	
	/***
	 * 
	 * @param cid,name
	 * @return
	 */
	@RequestMapping(value = "/channelGoods/list", method = RequestMethod.GET)
	public @ResponseBody Object list(ChannelGoodsQuery query) {
		log.info("into artwork post.channelGoods.list: " + query);
		return service.getChannelsGoodsByPage(query);
	}
	
}
